<?php
class Controller{
	
	public $name = null;
	public $app = null;
	public $err = null;
	public $layout = null;
	public $template = null;
	public $params = null;
	public $mapping = null;
	public $rendered = null;
	public $vars = null;
	
	public function init($modules, $mapping){
		$this->rendered = false;
		$this->layout = 'default';
		$this->vars = array();
		//init modules
		foreach($modules as $module){
			$this->$module = $this->app->$module;
		}
		//assign mapping
		$this->mapping = $mapping;
		//init params
		if($mapping['params']){
			$_GET = array_merge($mapping['params'], $_GET);
		}
		$this->params = $_GET;
		$this->common();
		$this->call_method($mapping['method'], $mapping['method_params']);
		if(!$this->rendered) $this->render();
	}
	
	public function before_render(){}
	
	public function render($file=null, $root=false){
		if($this->rendered) return false;
		//decide which file to render
		$base_tpl_dir = ($root ? TPL_PATH : APP_TPL_PATH);
		if($file) $file = $base_tpl_dir.$file;
		else $file = $base_tpl_dir.$this->mapping['controller'].'/'.$this->mapping['method'].'.html';
		if(!file_exists($file)) $this->err->fatal_error('Cannot render. File <strong>'.$file.'</strong> does not exist.');
		//prepare layout
		$layout_file = APP_TPL_PATH.'layouts/'.$this->layout.'.html';
		if(!file_exists($layout_file)) $this->err->fatal_error('Cannot render. Layout <strong>'.$layout_file.'</strong> does not exist.');
		
		$this->before_render();
		
		$this->parser->vars = $this->vars;
		$this->parser->load('content', $file);
		$html = $this->parser->parse('main', $layout_file);
		if(TPL_GATHER_CSS) $html = $this->parser->gather_css($html);
		$html = $this->post_process($html);
		echo $html;
		
		$this->rendered = true;
		$this->after_render();
	}
	
	public function post_process($html){
		return $html;
	}
	
	public function after_render(){}
	
	public function call_method($name, $params){
		call_user_func_array(array($this,$name), $params);
	}
	
	public function set($name, $value){
		$this->vars[$name] = $value;
	}
	
	public function get($name){
		return $this->vars[$name];
	}
	
	public function parse_loop($name, $values){
		if($this->app->module_loaded('parser'))
			$this->parser->parse_loop($name, $values);
	}
	
	public function common(){} //prototype for AppController
	
}
?>